#!/usr/bin/env python
# coding:utf-8
'''
DMZ资源每日统计，包括模式 玩法 歌曲 场景
'''
import os,sys,datetime,common.db
from logging import *
from common.date_time import *

def get_task_music():
    # 获取xml
    from urllib import urlopen
    try:
        file_xml=urlopen('http://114.80.90.156/quest.xml')
    except IOException:
        log('get xml failed.\n');
        return ''

    # 解析xml
    from xml.etree import ElementTree
    tree=ElementTree.parse(file_xml)
    runcond_all=tree.findall('./quest/runcond')
    result=[]
    for runcond in runcond_all:
        attribute=runcond.attrib
        if attribute.has_key('game_play') and attribute.has_key('music_id'):
            result.append('(%s,%s)'%(attribute['game_play'],attribute['music_id']))
    return ','.join(result)


def ResourceStatDay(strCurDay):
    log(INFO,'StatDay : '+ strCurDay)
    strDay = strCurDay.replace('-','')
 
    task_music=get_task_music()
    if len(task_music)>0:
        task_music_sql_condition        ='where (GamePlay,MusicID) in (%s)'%(task_music)
        nontask_music_sql_condition     ='where (GamePlay,MusicID) not in (%s)'%(task_music)
    else:
        task_music_sql_condition        =''
        nontask_music_sql_condition     =''

    # 连接数据库
    cnn = common.db.connect('billDB')
    cur = cnn.cursor()

    # 清除当天已有数据
    strSql = 'delete from statisticdb.DMZResourceDay where `date`=%s'%(strDay)
    rowsDeleted = cur.execute(strSql)
    cnn.commit()
    if rowsDeleted>0:
        log(INFO,'deleted %d rows', rowsDeleted)       

    mode_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"Mode",ZoneID,0,GameMode,count(*) from dmz_bill_%s.game
            group by ZoneID,GameMode 
            '''%(strDay,strDay)

    music_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"Music",ZoneID,GamePlay,MusicID,count(*) from dmz_bill_%s.game %s
            group by ZoneID,GamePlay,MusicID
             '''%(strDay,strDay,nontask_music_sql_condition)

    task_music_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"TaskMusic",ZoneID,GamePlay,MusicID,count(*) from dmz_bill_%s.game %s
            group by ZoneID,GamePlay,MusicID
             '''%(strDay,strDay,task_music_sql_condition)

    scene_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"Scene",ZoneID,0,SceneID,count(*) from dmz_bill_%s.game
            group by ZoneID,SceneID
            '''%(strDay,strDay)

    player_count_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"Count",ZoneID,0,PlayerCount,count(*) from dmz_bill_%s.game
            group by ZoneID,PlayerCount
            '''%(strDay,strDay)

    music_star_sql='''insert into statisticdb.DMZResourceDay (Date,Object,ZoneID,GamePlay,ID,Count) 
            select %s,"Star",ZoneID,GamePlay,MusicStar,count(*) from dmz_bill_%s.game 
            group by ZoneID,GamePlay,MusicStar
            '''%(strDay,strDay)
    try:
        cur.execute(mode_sql)
        cur.execute(music_sql)
        cur.execute(task_music_sql)
        cur.execute(scene_sql)
        cur.execute(player_count_sql)
        cur.execute(music_star_sql)
    except Exception,data:
        log(ERROR,data)
        sys.exit(0)
        
    cnn.commit()
    cur.close()
    cnn.close()
                    

if __name__ != "__main__":

    # 检验输入参数,如果参数为空,返回昨天日期
    if len(sys.argv) > 3:
        strBeginDay = sys.argv[2]
        strEndDay = sys.argv[3]
        if len(strBeginDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        if len(strEndDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        for strCurDay in intervalDay(strBeginDay,strEndDay):
            ResourceStatDay(strCurDay)
    elif len(sys.argv) > 2:
        strCurDay = sys.argv[2]
        if len(strCurDay) != 10:
            log(ERROR,'Param is error!')
            sys.exit(0)
        ResourceStatDay(strCurDay)
    else:
        strCurDay = GetDay(-1) ##"2010-01-14"
        ResourceStatDay(strCurDay)




